package util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import entity.ParsePlayCount;
import entity.ParsePlayTime;
import entity.ParseSearchKey;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class AnalysisUtil {
    public static final SimpleDateFormat FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
    public static final SimpleDateFormat TARGETFORMAT = new SimpleDateFormat(
            "yyyyMMddHHmmss");

    private static Date parseDateFormat(String string) {
        Date parse = null;
        try {
            parse = FORMAT.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }

    private static String parseEvent(String line) {
        final int first = line.indexOf("[ INFO ]  [") + "[ INFO ]  [".length();
        final int last = line.indexOf("]", first);
        return line.substring(first, last).trim();
    }

    private static String parseDate(String line) {
        final int first = 0;
        final int last = line.indexOf("[");
        return line.substring(first, last).trim();
    }

    public static JsonObject AppLogAnalysis() {
        JsonObject data = new JsonObject();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(
                    System.getProperty("user.dir") + "\\logs", "log.log"
            ))));
            System.out.println("Get log file: " + System.getProperty("user.dir") + "\\logs\\log.log");
            List<ParseSearchKey> searchKeys = new ArrayList<>();
            List<ParsePlayCount> playCount = new ArrayList<>();
            List<ParsePlayTime> playTime = new ArrayList<>();
            for(int i = 0; i < 24; i++) playTime.add(new ParsePlayTime(i));
            JsonArray favorite = new JsonArray();

            String line = null;
            while ((line = br.readLine()) != null) {
                try {
                    String event = parseEvent(line);
                    Date time = parseDateFormat(parseDate(line));
                    JsonObject content =
                            new JsonParser().parse(
                                    line.substring(
                                            line.indexOf("{"),
                                            line.lastIndexOf("}") + 1)).getAsJsonObject();
                    content.addProperty("time", time.getTime());
                    if (event.equals("Search") && content.get("error") == null) {
                        String[] keys = new Gson().fromJson(content.get("key").getAsJsonArray(), String[].class);
                        for (String s : keys) {
                            int index = -1;
                            for(int i = 0; i < searchKeys.size(); i++) {
                                if(searchKeys.get(i).getKey().equals(s.toLowerCase())) {
                                    index = i;
                                    break;
                                }
                            }
                            if(index == -1) {
                                System.out.println("New key: " + s);
                                ParseSearchKey k = new ParseSearchKey(s.toLowerCase());
                                searchKeys.add(k);
                                index = searchKeys.size() - 1;
                            }
                            searchKeys.get(index).addCount();
                        }
                    } else if (event.equals("Play video") && content.get("error") == null) {
                        int index = -1;
                        int vid = content.get("id").getAsInt();
                        String username = content.get("from").getAsString();
                        for (int i = 0; i < playCount.size(); i++) {
                            if (playCount.get(i).getVid() == vid) {
                                index = i;
                                break;
                            }
                        }
                        if (index == -1) {
                            ParsePlayCount p = new ParsePlayCount(vid);
                            playCount.add(p);
                            index = playCount.size() - 1;
                        }
                        ParsePlayCount p = playCount.get(index);
                        p.setCount(p.getCount() + 1);
                        if (p.getUsername().indexOf(username) == -1) {
                            List<String> tempList = p.getUsername();
                            tempList.add(username);
                            p.setUsername(tempList);
                            p.setNoRepeatCount(p.getNoRepeatCount() + 1);
                        }
                        playTime.get(time.getHours()).addPlayCount();
                    } else if (event.equals("Favorite") && content.get("error") == null) {
                    }
                } catch (Exception e) {
                }
            }

            data.add("playCount", new Gson().toJsonTree(playCount));
            data.add("playTime", new Gson().toJsonTree(playTime));
            data.add("searchKeys", new Gson().toJsonTree(searchKeys));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}
